package com.capgemini.poste.metier;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.capgemini.poste.dao.Event;
import com.capgemini.poste.dao.Poste;

public class Workstation extends com.capgemini.poste.dao.Poste {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6497992434105396667L;
	static HashSet<Poste> postes = new HashSet<Poste>() ;
	
	public Workstation( EntityManager em ) {
		
		// Create the query and populate the HashSet with workstations retrieved from DTB
		Query getAllPoste = em.createQuery("select p from Poste p") ;
		@SuppressWarnings("unchecked")
		List<Poste> results = getAllPoste.getResultList() ;
		for ( Poste result : results ) {
			postes.add(result) ;
		}

	}

	public ArrayList<Event> retrieve (XSSFSheet excelSheet ) {
		// TODO Auto-generated method stub
		XSSFRow row;
		boolean bFirst = true ;
		ArrayList<Event> events = new ArrayList<Event> () ;

		for (Iterator<Row> rowIterator = excelSheet.rowIterator(); rowIterator.hasNext();) {
			row = (XSSFRow) rowIterator.next();
            // Skip the header row
			if ( bFirst == true) {
               row = (XSSFRow) rowIterator.next();
               bFirst = false ;
            }
			
			Poste poste = new Poste();
			// Colonne 0 = Code du poste
			if ( row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC ){
				poste.setCd(String.valueOf(row.getCell(0).getNumericCellValue()));
			}
			else {	
				poste.setCd(row.getCell(0).getStringCellValue().toUpperCase());
			}
				
			// Colonne 2 = IP du poste
			poste.setLbIp(row.getCell(2).getStringCellValue());

			// Use a HashSet avoid multiple records
			if ( postes.add(poste) == true ) {
				System.out.println ( "PC " + poste.getCd() + " (" + poste.getLbIp() + ") has been added !!");
				Event event = new Event () ;
				event.setType(POSTE.WORKSTATION) ;
				event.setCd(poste.getCd()) ;
				events.add(event) ;
			}

		}
		return events ;
	}

	public ArrayList<Event> retrieve (XSSFWorkbook excelWorkbook ) {
		// TODO Auto-generated method stub
		ArrayList<Event> events = new ArrayList<Event> () ;

		events = this.retrieve(excelWorkbook.getSheetAt(0)) ;
		events.addAll(this.retrieve(excelWorkbook.getSheetAt(1))) ;
		events.addAll(this.retrieve(excelWorkbook.getSheetAt(2))) ;
		
		return events ;
	}
	
	public int getSize ( ) {
		return postes.size() ;
	}
	
	public void save ( EntityManager em ) {
		for ( Iterator<Poste> p = postes.iterator(); p.hasNext() ;) {
			em.persist(p.next()) ;
		}
	}
}
